package com.tpddns.flannery.flanneryscreenshots;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initListView();
        initGetPictureButton();
        findViewById(R.id.permission).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initPermission();
            }
        });
        initJumpWeChate();
        initDecorderView();
    }

    //跳转到DecoderView
    private void initDecorderView() {
        findViewById(R.id.screenShotDecoderVeiw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View dView = MyApplication.mActivityInstance.getWindow().getDecorView();
                dView.setDrawingCacheEnabled(true);
                dView.buildDrawingCache();
                Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache());
                if (bitmap != null) {
                    try {
                        // 获取内置SD卡路径
                        String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                        // 图片文件路径
                        String filePath = sdCardPath + File.separator + "screenshot.png";
                        File file = new File(filePath);
                        FileOutputStream os = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                        os.flush();
                        os.close();
                        //DebugLog.d("a7888", "存储完成");
                    } catch (Exception e) {
                    }
                }
//                View decorView = getWindow().getDecorView().getRootView().findViewById(R.id.mainActivity);
//                Bitmap bitmapCompress = MainActivity.createBitmapSimpleView(decorView, MyApplication.mActivityInstance);
//
//                MainActivity.saveImageToGallery(MyApplication.mActivityInstance, bitmapCompress, "/images");
            }
        });
    }

    // 跳转到微信朋友圈　
    private void initJumpWeChate() {
        findViewById(R.id.jumpWeChat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    private void initPermission() {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    private String[][] data = new String[][]{
            {"冲30", "到账300V币", "折合1毛钱/分钟，有效期三个月", "30"},
            {"冲50", "送20元,到账700V币", "折合7分钱/分钟，有效期6个月", "50"},
            {"冲100", "送60元,到账1600V币", "折合6分钱/分钟，有效期一年", "100"},
            {"冲200", "送200元,到账4000V币", "折合5分钱/分钟，有效期两年", "200"},
            {"冲30", "到账300V币", "折合1毛钱/分钟，有效期三个月", "30"},
            {"冲50", "送20元,到账700V币", "折合7分钱/分钟，有效期6个月", "50"},
            {"冲100", "送60元,到账1600V币", "折合6分钱/分钟，有效期一年", "100"},
            {"冲200", "送200元,到账4000V币", "折合5分钱/分钟，有效期两年", "200"},
            {"冲30", "到账300V币", "折合1毛钱/分钟，有效期三个月", "30"},
            {"冲50", "送20元,到账700V币", "折合7分钱/分钟，有效期6个月", "50"},
            {"冲100", "送60元,到账1600V币", "折合6分钱/分钟，有效期一年", "100"},
            {"冲200", "送200元,到账4000V币", "折合5分钱/分钟，有效期两年", "200"},
            {"冲30", "到账300V币", "折合1毛钱/分钟，有效期三个月", "30"},
            {"冲50", "送20元,到账700V币", "折合7分钱/分钟，有效期6个月", "50"},
            {"冲100", "送60元,到账1600V币", "折合6分钱/分钟，有效期一年", "100"},
            {"冲200", "送200元,到账4000V币", "折合5分钱/分钟，有效期两年", "200"},
            {"冲30", "到账300V币", "折合1毛钱/分钟，有效期三个月", "30"},
            {"冲50", "送20元,到账700V币", "折合7分钱/分钟，有效期6个月", "50"},
            {"冲100", "送60元,到账1600V币", "折合6分钱/分钟，有效期一年", "100"},
            {"冲200", "送200元,到账4000V币", "折合5分钱/分钟，有效期两年", "200"},
            {"冲30", "到账300V币", "折合1毛钱/分钟，有效期三个月", "30"},
            {"冲50", "送20元,到账700V币", "折合7分钱/分钟，有效期6个月", "50"},
            {"冲100", "送60元,到账1600V币", "折合6分钱/分钟，有效期一年", "100"},
            {"冲200", "送200元,到账4000V币", "折合5分钱/分钟，有效期两年", "200"},
            {"冲300", "送450元,到账7500V币", "折合4毛钱/分钟，有效期两年", "300"}
    };

    private int[] imageIds = new int[]{
            R.drawable.abc_btn_check_to_on_mtrl_000,
            R.drawable.abc_btn_check_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000,
            R.drawable.abc_btn_radio_to_on_mtrl_015,
            R.drawable.abc_btn_check_to_on_mtrl_000,
            R.drawable.abc_btn_check_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000,
            R.drawable.abc_btn_radio_to_on_mtrl_015,
            R.drawable.abc_btn_check_to_on_mtrl_000,
            R.drawable.abc_btn_check_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000,
            R.drawable.abc_btn_radio_to_on_mtrl_015,
            R.drawable.abc_btn_check_to_on_mtrl_000,
            R.drawable.abc_btn_check_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000,
            R.drawable.abc_btn_radio_to_on_mtrl_015,
            R.drawable.abc_btn_check_to_on_mtrl_000,
            R.drawable.abc_btn_check_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000,
            R.drawable.abc_btn_radio_to_on_mtrl_015,
            R.drawable.abc_btn_check_to_on_mtrl_000,
            R.drawable.abc_btn_check_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000,
            R.drawable.abc_btn_radio_to_on_mtrl_015,
            R.drawable.abc_btn_radio_to_on_mtrl_000
    };


    private void initGetPictureButton() {
        Button getPicture = findViewById(R.id.getPicture);

        getPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ListView listView = (ListView) getWindow().getDecorView().findViewById(R.id.myListView);
                //ListView listView = findViewById(R.id.myListView);
                // 获取截屏
                Bitmap bitmap = createBitmap(listView, MainActivity.this);
                // 压缩图片
                Bitmap bitmapCompress = compressImage(bitmap);
                // 存储图片
                saveImageToGallery(MainActivity.this, bitmapCompress, "/images");
            }
        });
    }

    private void initListView() {
        ListView listView = findViewById(R.id.myListView);

        //创建一个List集合，List集合的元素是map
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
        //利用循环将键和值一一对应放入集合内。
        for (int i = 0; i < data.length; i++) {
            Map<String, Object> listItem = new HashMap<String, Object>();
            listItem.put("header", imageIds[i]);//这里图片数组
            listItem.put("money", data[i][0]);
            listItem.put("amount", data[i][1]);
            listItem.put("desc", data[i][2]);
            listItem.put("end", data[i][3]);

            listItems.add(listItem);

        }


        SimpleAdapter simpleadapter = new SimpleAdapter(this, listItems,
                R.layout.simple_item, new String[]{"header", "money", "amount", "desc", "money2"},
                new int[]{R.id.hander, R.id.money, R.id.amount, R.id.desc, R.id.end,});

        listView.setAdapter(simpleadapter);
    }


    // 截图及图片处理

    /**
     * ListView 截屏
     *
     * @param listView
     * @param context
     * @return
     */
    public static Bitmap createBitmap(ListView listView, Context context) {
        int titleHeight, width, height, rootHeight = 0;
        Bitmap bitmap;
        Canvas canvas;
        int yPos = 0;
        int listItemNum;
        List<View> childViews = null;

        width = getDisplayMetrics(context)[0];//宽度等于屏幕宽

        ListAdapter listAdapter = listView.getAdapter();
        listItemNum = listAdapter.getCount();
        childViews = new ArrayList<View>(listItemNum);
        View itemView;
        //计算整体高度:
        for (int pos = 0; pos < listItemNum; ++pos) {
            itemView = listAdapter.getView(pos, null, listView);
            //measure过程
            itemView.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            childViews.add(itemView);
            rootHeight += itemView.getMeasuredHeight();
        }

        height = rootHeight;
        // 创建对应大小的bitmap
        int widthListViewGetWidth = listView.getWidth();
        bitmap = Bitmap.createBitmap(widthListViewGetWidth, height, Bitmap.Config.ARGB_8888);
        //bitmap = BitmapUtil.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        Bitmap itemBitmap;
        int childHeight;
        //把每个ItemView生成图片，并画到背景画布上
        for (int pos = 0; pos < childViews.size(); ++pos) {
            itemView = childViews.get(pos);
            childHeight = itemView.getMeasuredHeight();
            itemBitmap = viewToBitmap(itemView, width, childHeight);
            if (itemBitmap != null) {
                canvas.drawBitmap(itemBitmap, 0, yPos, null);
            }
            yPos = childHeight + yPos;
        }

        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bitmap;
    }


    // 创建单个的View
    public static Bitmap createBitmapSimpleView(View view, Context context) {
        Bitmap bitmap;
        Canvas canvas;

        // 创建对应大小的bitmap
        int widthListViewGetWidth = view.getWidth();
        int widthListViewGetHeight = view.getHeight();
        bitmap = Bitmap.createBitmap(widthListViewGetWidth, widthListViewGetHeight, Bitmap.Config.ARGB_8888);
        //bitmap = BitmapUtil.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        //canvas.drawColor(Color.WHITE);

        Bitmap itemBitmap = viewToBitmap(view, widthListViewGetWidth, widthListViewGetHeight);
        if (bitmap != null) {
            canvas.drawBitmap(itemBitmap, 0, widthListViewGetHeight, null);
        }

        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bitmap;
    }


    // 获取View的截图
    public static Bitmap viewToBitmap(View view, int viewWidth, int viewHeight) {
        view.layout(0, 0, viewWidth, viewHeight);
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }


    /**
     * 压缩图片
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 100) {
            // 重置baos
            baos.reset();
            // 这里压缩options%，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            // 每次都减少10
            options -= 10;
        }
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }


    /**
     * 获取屏幕分辨率
     *
     * @param context
     * @return
     */
    public static final Integer[] getDisplayMetrics(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        return new Integer[]{screenWidth, screenHeight};
    }


    /**
     * 保存图片并插入图库
     *
     * @param context
     * @param bmp
     * @param dir     文件夹
     */
    public static void saveImageToGallery(Context context, Bitmap bmp, String dir) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), dir);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        String path = appDir + fileName;
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }

    private void test() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);


        AccessibilityNodeInfo accessibilityNodeInfo=null;


        Rect outBounds = new Rect();
        accessibilityNodeInfo.getBoundsInParent(outBounds); //获取这个View的位置
    }

}
